package zbum.issue.cmmn.web;

import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.AbstractView;

import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo;

public class JqgridXmlView extends AbstractView {

	public String getContentType() {
		return "text/xml;charset=utf-8";
	}

	@Override
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		

		
		StringBuffer sb = new StringBuffer();
		List<?> jqgridData = (List<?>)model.get("jqgrid_data");
		String[] colOrder = (String[])model.get("jqgrid_columns");
		String page = (String)model.get("page");
		Integer total = (Integer)model.get("total");
		Integer records = (Integer)model.get("records");
				
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
		sb.append("<rows>\n");
		sb.append("  <page>").append(page).append("</page>\n");
		sb.append("  <total>").append(total).append("</total>\n");
		sb.append("  <records>").append(records).append("</records>\n");
		
		for( int inx=0 ; inx < jqgridData.size() ; inx++ ) {
			
			Object data = jqgridData.get(inx);
			
			if ( data instanceof Map){
				Map mapData = (Map)data;
				sb.append("  <row id=\"").append(mapData.get(colOrder[0])).append("\" >\n");
				for ( String key : colOrder ) {
					sb.append("    <cell>"+mapData.get(key)+"</cell>");
				}
				sb.append("  </row>\n");
			}else{
				Class clazz = data.getClass();
				
				sb.append("  <row id=\"2010-2\" >\n");
				for ( int jnx=0 ; jnx < colOrder.length ; jnx++ ){
					Field field = clazz.getDeclaredField(colOrder[jnx]);
					sb.append("    <cell>"+field.get(data)+"</cell>");
				}
				sb.append("  </row>\n");
			}
			
		}
		sb.append("</rows>");
		
		response.setContentType(getContentType());
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		response.setContentLength(sb.toString().getBytes("utf-8").length);
		
		
		PrintWriter pw = response.getWriter();
		pw.write(sb.toString());
		pw.close();
		pw.flush();
		
	}

}
